package com.chang.bootplus.config.security;

import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//	@Autowired
//	CaptchaFilter captchaFilter;

	@Autowired
	JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

	@Autowired
	LoginFailureHandler loginFailureHandler;

	@Autowired
	LoginSuccessHandler loginSuccessHandler;

	@Autowired
	UserDetailServiceImpl userDetailService;

	@Autowired
	JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

	@Autowired
	JwtAccessDeniedHandler jwtAccessDeniedHandler;

	@Autowired
	JwtUtils jwtUtils;

	@Bean
	JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
		// 当前的kwtFilter需要注入权限管理器
		JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
		return jwtAuthenticationFilter;
	}

	@Bean
	BCryptPasswordEncoder bCryptPasswordEncoder() {
		return new BCryptPasswordEncoder();
	}

	private static final String[] URL_WHITELIST = {
			"/schoolLogin",
			"/school/register",
			"/wx-user/**",
			"/logout",
			"/student/verify",
			"/student/binding",
			"/test",
			"/student/listresult",
			"/getLevel",
			"/**",
			"/user/register",
			"/swagger-resources/**",
			"/swagger-ui.html",
			"/v2/api-docs",
			"/swagger/**",
			"/v2**",
			"/webjars/**",
			// swagger-boostrap-ui
			"/doc.html"
	};



	@Override
	protected void configure(HttpSecurity http) throws Exception {

		http.cors().and().csrf().disable()
				.sessionManagement()
				.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				// 配置拦截规则
				.and()
				.authorizeRequests()
				// 允许白名单
				.antMatchers(URL_WHITELIST).permitAll()
				.anyRequest().authenticated()
				// 异常处理器
				.and()


				// 登录配置
				.formLogin().loginPage("/schoolLogin")
				.and()
				.logout()
				.logoutSuccessHandler(jwtLogoutSuccessHandler)
				// 禁用session
				.and()
				.exceptionHandling()
				.authenticationEntryPoint(jwtAuthenticationEntryPoint)
				// jwt出现的异常处理器
				.accessDeniedHandler(jwtAccessDeniedHandler)
				// 配置自定义的过滤器
				.and()
				.addFilter(jwtAuthenticationFilter())
				.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
//				.addFilterBefore(captchaFilter,UsernamePasswordAuthenticationFilter.class);
	}


	@Bean
	CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
		CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
		filter.setAuthenticationSuccessHandler(loginSuccessHandler);
		filter.setAuthenticationFailureHandler(loginFailureHandler);
		filter.setAuthenticationManager(authenticationManagerBean());
		filter.setFilterProcessesUrl("/schoolLogin");
		return filter;
	}



	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailService);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		//allow Swagger URL to be accessed without authentication
		web.ignoring().antMatchers("/v2/api-docs",//swagger api json
				"/swagger-resources/configuration/ui",//用来获取支持的动作
				"/swagger-resources",//用来获取api-docs的URI
				"/swagger-resources/configuration/security",//安全选项
				"/swagger-ui.html", "/doc.html");
	}
}
